package cn.supermaster.management.core.manager;

import java.util.Date;
import java.util.TimerTask;

import cn.supermaster.management.common.enums.OnlineStatus;
import cn.supermaster.management.core.session.OnlineSession;
import cn.supermaster.management.system.service.impl.SystemLoginInformationServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.supermaster.management.common.constant.Constants;
import cn.supermaster.management.common.utils.AddressUtils;
import cn.supermaster.management.common.utils.LogUtils;
import cn.supermaster.management.common.utils.ServletUtils;
import cn.supermaster.management.common.utils.ShiroUtils;
import cn.supermaster.management.common.utils.TextUtils;
import cn.supermaster.management.common.utils.spring.SpringUtils;
import cn.supermaster.management.system.domain.SysLogininfor;
import cn.supermaster.management.system.domain.SystemOperateLog;
import cn.supermaster.management.system.domain.SystemUserOnline;
import cn.supermaster.management.system.service.ISystemOperateLogService;
import cn.supermaster.management.system.service.ISystemUserOnlineService;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.core.manager
 * @ClassName: AsynchronousFactory
 * @Description: [异步工厂（产生任务用）]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/10 22:24
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.comn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
public class AsynchronousFactory {

    /**
     * 获取用户日志对象
     **/
    private static final Logger logger = LoggerFactory.getLogger("sys-user");

    /**
     * @Description: [同步session到数据库]
     * <p></P>
     * @Title: syncSessionToDb
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: session 在线用户会话
     * @Return: java.util.TimerTask 任务task
     */
    public static TimerTask syncSessionToDb(final OnlineSession session) {
        // 获取session属性值
        String sessionId = String.valueOf(session.getId());//session主键
        String deptName = session.getDeptName();// 部门名称
        String userName = session.getuserName();// 用户名称
        Date startTimestamp = session.getStartTimestamp();// 开始时间
        Date lastAccessTime = session.getLastAccessTime();// 最后登录时间
        long expireTime = session.getTimeout();// 超时时间
        String host = session.getHost();// 主机信息
        String address = AddressUtils.getRealAddressByIP(session.getHost());//ip地址
        String browser = session.getBrowser();// 浏览器信息
        String os = session.getOs();// 操作系统信息
        OnlineStatus status = session.getStatus();// session状态
        // 获取对象
        ISystemUserOnlineService userOnlineService = SpringUtils.getBean(ISystemUserOnlineService.class);
        //
        return new TimerTask() {
            @Override
            public void run() {
                SystemUserOnline online = new SystemUserOnline(sessionId, deptName, userName, host, address,
                        browser, os, startTimestamp, lastAccessTime, expireTime, status);
                //
                userOnlineService.saveOnline(online);
            }
        };
    }

    /**
     * @Description: [操作日志记录]
     * <p></P>
     * @Title: recordOper
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: operLog  操作日志信息
     * @Return: java.util.TimerTask 任务task
     */
    public static TimerTask recordOperateLog(final SystemOperateLog operateLog) {
        String operateIp = operateLog.getOperIp();
        String address = AddressUtils.getRealAddressByIP(operateIp);
        // 远程查询操作地点
        operateLog.setOperLocation(address);
        ISystemOperateLogService operateLogService = SpringUtils.getBean(ISystemOperateLogService.class);
        //
        return new TimerTask() {
            @Override
            public void run() {
                operateLogService.insertOperlog(operateLog);
            }
        };
    }

    /**
     * @Description: [记录登录信息]
     * <p></P>
     * @Title: recordLogininfor
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: username  用户名
     * @Param: status  状态
     * @Param: message 消息
     * @Param: args 参数列表
     * @Return: java.util.TimerTask 任务task
     * @Throws:
     */
    public static TimerTask recordLoginInformation(final String username, final String status, final String message,
                                                   final Object... args) {
        String header = ServletUtils.getRequest().getHeader("User-Agent");
        final UserAgent userAgent = UserAgent.parseUserAgentString(header);
        //
        SystemLoginInformationServiceImpl loginInformationService = SpringUtils.getBean(SystemLoginInformationServiceImpl.class);
        final String ip = ShiroUtils.getIp();
        String address = AddressUtils.getRealAddressByIP(ip);

        StringBuilder builder = new StringBuilder();
        builder.append(LogUtils.buildBlock(ip));
        builder.append(address);
        builder.append(LogUtils.buildBlock(username));
        builder.append(LogUtils.buildBlock(status));
        builder.append(LogUtils.buildBlock(message));

        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLogininfor logininfor = new SysLogininfor(null, username, null, ip, address, browser, os,
                message, null);
        // 日志状态
        if (TextUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(Constants.FAIL);
        }

        return new TimerTask() {
            @Override
            public void run() {
                // 打印信息到日志
                logger.info(builder.toString(), args);
                // 插入数据
                loginInformationService.insertLogininfor(logininfor);
            }
        };
    }
}
